package com.myapp.controller;

import com.gitee.fastmybatis.core.PageInfo;
import com.gitee.fastmybatis.core.query.TenantQuery;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.query.param.PageParam;
import com.myapp.entity.TenantDemo;
import com.myapp.service.TenantDemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 演示多租户
 * <pre>
 *     关键配置在WebConfig、TenantInterceptor
 * </pre>
 * @author xxx
 */
@RestController
@RequestMapping("tenant")
public class TenantDemoController {

    private static Logger log = LoggerFactory.getLogger(TenantDemoController.class);

    @Autowired
    private TenantDemoService tenantDemoService;

    /**
     * 分页查询
     * <p>
     *     http://localhost:8080/tenant/page?pageIndex=1&tenantId=a100001
     * </p>
     * @param param
     * @return
     */
    @GetMapping("/page")
    public PageInfo<TenantDemo> page(PageParam param) {
        TenantQuery query = param.toTenantQuery();
        log.info("是否设置了多租户id：{}, tenantId -> {}", query.existTenantValue(), query.getTenantValue());
        return tenantDemoService.page(query);
    }

    /**
     * http://localhost:8080/tenant/list?tenantId=a100001
     * http://localhost:8080/tenant/list?tenantId=a100001&name=Jim
     * @return
     */
    @GetMapping("/list")
    public List<TenantDemo> list(@RequestParam(required = false) String name) {
        // 使用TenantQuery表示使用了多租户查询
        TenantQuery query = new TenantQuery();
        // 添加其它查询条件
        query.eq(name != null, "name", name);
        log.info("是否设置了多租户id：{}, tenantId -> {}", query.existTenantValue(), query.getTenantValue());
        return tenantDemoService.list(query);
    }

    /**
     * 不走多租户
     * http://localhost:8080/tenant/normal?tenantId=a100001
     * @return
     */
    @GetMapping("/normal")
    public List<TenantDemo> normal() {
        // 不使用TenantQuery，走正常查询
        Query query = new Query();
        return tenantDemoService.list(query);
    }
    
}